package util;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ListSortUtil<T> {
	
	
	@SuppressWarnings({ "unchecked", "rawtypes" })  
    public static void sortString(List targetList, final String sortField, final String sortMode) {  
      
        Collections.sort(targetList, new Comparator() {  
            public int compare(Object obj1, Object obj2) {   
                int retVal = 0;  
                try {  
                    //首字母转大写  
                    String newStr=sortField.substring(0, 1).toUpperCase()+sortField.replaceFirst("\\w","");   
                    String methodStr="get"+newStr;  
                      
                    Method method1 = obj1.getClass().getMethod(methodStr, null);  
                    Method method2 = obj2.getClass().getMethod(methodStr, null);  
                    if (sortMode != null && "desc".equals(sortMode)) {  
                        retVal = method2.invoke(obj2, null).toString().compareTo(method1.invoke(obj1, null).toString()); // 倒序  
                    } else {  
                        retVal = method1.invoke(obj1, null).toString().compareTo(method2.invoke(obj2, null).toString()); // 正序  
                    }  
                } catch (Exception e) {  
                    throw new RuntimeException();  
                }  
                return retVal;  
            }  
        });  
    }  
	@SuppressWarnings({ "unchecked", "rawtypes" })  
	public static void sortNum(List targetList, final String sortField, final String sortMode) {  
		
		Collections.sort(targetList, new Comparator() {  
			public int compare(Object obj1, Object obj2) {   
				int retVal = 0;  
				try {  
					//首字母转大写  
					String newStr=sortField.substring(0, 1).toUpperCase()+sortField.replaceFirst("\\w","");   
					String methodStr="get"+newStr;  
					
					Method method1 = (obj1).getClass().getMethod(methodStr, null);  
					Method method2 = (obj2).getClass().getMethod(methodStr, null);  
					if (sortMode != null && "desc".equals(sortMode)) {  
						retVal = (int) (Double.parseDouble(method2.invoke(obj2, null).toString()) - Double.parseDouble(method1.invoke(obj1, null).toString())); // 倒序  
					} else {  
						retVal =  (int) (Double.parseDouble(method1.invoke(obj1, null).toString()) - Double.parseDouble(method2.invoke(obj2, null).toString()));  // 正序  
					}  
				} catch (Exception e) {  
					throw new RuntimeException();  
				}  
				return retVal;  
			}  
		});  
	}  
}
